package view.menu;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;

import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.SwingConstants;
import java.awt.Component;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JButton;
import javax.swing.border.LineBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.Document;

import entiey.Dictionary;
import entiey.Menu;
import entiey.TypeId;
import service.DictionaryService;
import service.MenuService;
import service.impl.DictionaryServiceImpl;
import service.impl.MenuServiceImpl;
import util.CastUtil;
import util.PinyinUtil;
import view.dic.V_Dictionary;

import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JCheckBox;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
 * 菜单的添加页面
 * @author 赵红娇
 * view.menu
 * @date 2020年8月30日下午5:39:51
 */
public class V_menuAdd extends JFrame {

	private JPanel contentPane;
	private JTextField text_id;
	private JTextField text_foodName;
	private JTextField text_spellCode;
	private JTextField text_foodPrice;
	private JEditorPane ep_desc;
	private JCheckBox cb_status;
	private JButton btn_add;
	private JEditorPane ep_remark;
	private JLabel lbl_icon;
	private MenuService menuService=new MenuServiceImpl();
	
	private File menuIcon;
	private JComboBox<Dictionary> cb_type;
	private boolean flag=false;
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					V_menuAdd frame = new V_menuAdd();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	/**
	 * Create the frame.
	 */
	public V_menuAdd() {
		setTitle("菜品信息");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 499, 389);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JLabel lblNewLabel = new JLabel("编号:");
		lblNewLabel.setBounds(22, 26, 69, 18);
		lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 15));
		
		text_id = new JTextField();
		text_id.setBounds(101, 23, 115, 21);
		text_id.setEditable(false);
		text_id.setColumns(10);
		
		JLabel lblNewLabel_1 = new JLabel("菜品名称:");
		lblNewLabel_1.setBounds(22, 55, 69, 18);
		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 15));
		
		text_foodName = new JTextField();
		Document doc=text_foodName.getDocument();
		doc.addDocumentListener(new DocumentAdapter() {
			@Override
			public void removeUpdate(DocumentEvent e) {
				String pinyin=PinyinUtil.getPinyin(text_foodName.getText());
				text_spellCode.setText(pinyin);
			}
			@Override
			public void insertUpdate(DocumentEvent e) {
				String pinyin=PinyinUtil.getPinyin(text_foodName.getText());
				text_spellCode.setText(pinyin);
			}
		});
		
		
		text_foodName.setBounds(101, 54, 115, 21);
		text_foodName.setColumns(10);
		
		JLabel lblNewLabel_1_1 = new JLabel("拼音简码:");
		lblNewLabel_1_1.setBounds(22, 95, 69, 18);
		lblNewLabel_1_1.setFont(new Font("宋体", Font.PLAIN, 15));
		
		text_spellCode = new JTextField();
		text_spellCode.setBounds(101, 94, 115, 21);
		text_spellCode.setEditable(false);
		text_spellCode.setColumns(10);
		
		JLabel lblNewLabel_1_1_1 = new JLabel("类别:");
		lblNewLabel_1_1_1.setBounds(22, 133, 69, 18);
		lblNewLabel_1_1_1.setFont(new Font("宋体", Font.PLAIN, 15));
		
		JLabel lblNewLabel_2 = new JLabel("菜品价格:");
		lblNewLabel_2.setBounds(22, 175, 69, 18);
		lblNewLabel_2.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewLabel_2.setFont(new Font("宋体", Font.PLAIN, 15));
		
		text_foodPrice = new JTextField();
		text_foodPrice.setBounds(101, 172, 115, 21);
		text_foodPrice.setColumns(10);
		
		cb_type = new JComboBox<Dictionary>();
		cb_type.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				System.out.println(cb_type.getSelectedIndex());
			}
		});
		cb_type.setBounds(101, 131, 115, 23);
		contentPane.add(cb_type);
		//界面一打开就初始化下拉列表
		initCombox();
		
		JLabel lblNewLabel_2_1 = new JLabel("菜品描述:");
		lblNewLabel_2_1.setBounds(22, 206, 69, 18);
		lblNewLabel_2_1.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewLabel_2_1.setFont(new Font("宋体", Font.PLAIN, 15));
		contentPane.setLayout(null);
		contentPane.add(lblNewLabel_2_1);
		contentPane.add(lblNewLabel);
		contentPane.add(text_id);
		contentPane.add(lblNewLabel_1_1_1);
		contentPane.add(lblNewLabel_2);
		contentPane.add(text_foodPrice);
		contentPane.add(lblNewLabel_1_1);
		contentPane.add(text_spellCode);
		contentPane.add(lblNewLabel_1);
		contentPane.add(text_foodName);
		
		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0)));
		panel.setBounds(293, 23, 168, 119);
		contentPane.add(panel);
		panel.setLayout(new BorderLayout(0, 0));
		
		lbl_icon = new JLabel("双击上传菜品图片");
		lbl_icon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getClickCount()==2) {
					flag=true;
					//创建一个文件选择框对象
					JFileChooser jf=new JFileChooser();
					//显示文件选择框
					jf.showOpenDialog(V_menuAdd.this);
					//文件类型过滤器
					jf.setFileFilter(new FileNameExtensionFilter("jpg&png File","jpg","png"));
					//得到选择的文件
					menuIcon = jf.getSelectedFile();
					//如果文件存在
					if(jf.getSelectedFile()!=null && jf.getSelectedFile().exists()) {
						//创建一个icon图片
						ImageIcon icon=new ImageIcon(jf.getSelectedFile().getAbsolutePath());
						icon.setImage(icon.getImage().getScaledInstance(250, 179, 1));
						//给lbl标签添加一个icon图标
						lbl_icon.setIcon(icon);
					}
				}
			}
		});
		panel.add(lbl_icon, BorderLayout.CENTER);
		
		btn_add = new JButton("确定");
		btn_add.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//获取界面中用户输入的菜品信息
				Menu menu=new Menu();
				menu.setFoodName(text_foodName.getText());
				menu.setSpellCode(text_spellCode.getText());
				Dictionary dictionary= (Dictionary) cb_type.getSelectedItem();
				menu.setType(dictionary.getId());
				
				//判断用户是否双击上传头像（判断在修改的时候，用户是否修改图片或者添加的时候是否上传图片）
				if(flag==true) {
					//上传商品图片到项目menuImg文件夹下
					String dir=System.getProperty("user.dir");
					String last=dir+"/menuImg/"+CastUtil.format(new Date(), CastUtil.YEAR_PATTERN)+menuIcon.getName();//获取原文件名后缀
					//上传头像
					upload(menuIcon,last);
					//把当前存放的图片路径存入到数据库中
					menu.setFoodIcon(last);
				}else {
					//如果修改头像的话，直接回去图片背后的文本即可（应为在数据回显的时候，把数据库中存储的图片路径，显示到了图片所在的label标签的文本中）
					menu.setFoodIcon(lbl_icon.getText());
				}
				
				menu.setFoodPrice(CastUtil.castDouble(text_foodPrice.getText()));
				//是否上架
				if(cb_status.isSelected()) {
					menu.setStatus(1);
				}else {
					menu.setStatus(0);
				}
				menu.setDescription(ep_desc.getText());
				menu.setRemark(ep_remark.getText());
				//添加菜品
				if(text_id.getText().equals("")) {
					
					if(menuService.add(menu)) {
						JOptionPane.showMessageDialog(V_menuAdd.this, "新菜品添加成功","成功提示",JOptionPane.INFORMATION_MESSAGE);
						//添加成功之后需要,把界面上输入的内容全部清空
						clear();
						
					}else {
						JOptionPane.showMessageDialog(V_menuAdd.this, "新菜品添加失败","失败提示",JOptionPane.ERROR_MESSAGE);
					}
				}else {
					//修改菜品信息
					menu.setId(Integer.valueOf(text_id.getText()));
					//若果菜品图片改变的话(重新上传头像)
					//如果没改变的话，直接保存原来的路径
					//怎么判断是否上传图片了呢？在头像标签里加上一个boolean类型的值做标记
					if(menuService.update(menu)) {
						JOptionPane.showMessageDialog(V_menuAdd.this, "菜品信息修改成功","成功提示",JOptionPane.INFORMATION_MESSAGE);
						dispose();
					}else {
						JOptionPane.showMessageDialog(V_menuAdd.this, "菜品信息添加失败","失败提示",JOptionPane.ERROR_MESSAGE);
					}
				}
				
			}
		});
		btn_add.setIcon(new ImageIcon(V_menuAdd.class.getResource("/images/add.png")));
		btn_add.setFont(new Font("宋体", Font.PLAIN, 15));
		btn_add.setBounds(112, 315, 86, 27);
		contentPane.add(btn_add);
		
		JButton btn_cancel = new JButton("取消");
		btn_cancel.setIcon(new ImageIcon(V_menuAdd.class.getResource("/images/delete.png")));
		btn_cancel.setFont(new Font("宋体", Font.PLAIN, 15));
		btn_cancel.setBounds(237, 315, 86, 27);
		contentPane.add(btn_cancel);
		
		cb_status = new JCheckBox("是否上架");
		cb_status.setBounds(274, 173, 103, 23);
		contentPane.add(cb_status);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(101, 206, 146, 85);
		contentPane.add(scrollPane);
		
		ep_desc = new JEditorPane();
		scrollPane.setViewportView(ep_desc);
		
		JLabel lblNewLabel_2_1_1 = new JLabel("备注:");
		lblNewLabel_2_1_1.setHorizontalAlignment(SwingConstants.LEFT);
		lblNewLabel_2_1_1.setFont(new Font("宋体", Font.PLAIN, 15));
		lblNewLabel_2_1_1.setBounds(274, 213, 43, 18);
		contentPane.add(lblNewLabel_2_1_1);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(320, 211, 142, 80);
		contentPane.add(scrollPane_1);
		
		ep_remark = new JEditorPane();
		scrollPane_1.setViewportView(ep_remark);
		
		JLabel lblNewLabel_3 = new JLabel("");
		lblNewLabel_3.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				V_Dictionary dictionary=new V_Dictionary();
				dictionary.setBounds(V_menuAdd.this.getX(), V_menuAdd.this.getY(), dictionary.getWidth(), dictionary.getHeight());
				dictionary.setVisible(true);
				dictionary.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosed(WindowEvent e) {
						//初始化下拉选项框
						initCombox();
					}
				});
			}
		});
		lblNewLabel_3.setIcon(new ImageIcon(V_menuAdd.class.getResource("/images/add.png")));
		lblNewLabel_3.setBounds(226, 135, 21, 15);
		contentPane.add(lblNewLabel_3);
		
	}
	/**
	 * 上传头像到项目文件下的menuImg里，数据库记录的是文件的存储路径
	 * @param menuIcon 在电脑本地选择的文件
	 * @param last 保存文件的路径
	 */
	public void upload(File menuIcon,String last) {
		try {
			System.out.println(menuIcon);
			System.out.println(last);
			BufferedInputStream bis=new BufferedInputStream(new FileInputStream(menuIcon));
			BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(last))); 
			byte[] b=new byte[1024];
			int len;
			while((len=bis.read(b))!=-1) {
				bos.write(b,0,len);
			}
			bos.close();
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 添加完菜品后，清除添加界面上的数据
	 */
	public void clear() {
		text_foodName.setText("");
		text_foodPrice.setText("");
		text_spellCode.setText("");
		cb_status.setSelected(false);
		cb_type.setSelectedIndex(0);
		ep_desc.setText("");
		ep_remark.setText("");
		lbl_icon.setIcon(null);
	}
	/**
	 * 初始化类型下拉框
	 */
	public void initCombox() {
		//查询全部菜品类型
		DictionaryService service=new DictionaryServiceImpl();
		List<Dictionary> menuType = service.findDictionaryByTypeID(TypeId.菜单类别);
		//下拉框添加默认选项
		Dictionary dic=new Dictionary();
		dic.setId(-1);
		dic.setName("---请选择---");
		dic.setTypeid(TypeId.默认);
		menuType.add(0,dic);
		DefaultComboBoxModel<Dictionary> model=new DefaultComboBoxModel<>();
		for (Dictionary dictionary : menuType) {
			model.addElement(dictionary);
		}
		cb_type.setModel(model);
	}
	//点击修改的时候，初始化页面数据
	public void init(Menu menu) {
		text_id.setText(menu.getId()+"");
		text_foodName.setText(menu.getFoodName());
		text_spellCode.setText(menu.getSpellCode());
		//类别回显
		int dicId = menu.getType();
		DictionaryService service=new DictionaryServiceImpl();
		//如果类别的id大于0的话
		if(dicId>0) {
			Dictionary dictionaryById = service.getDictionaryById(dicId);
			cb_type.setSelectedItem(dictionaryById);
		}
		text_foodPrice.setText(menu.getFoodPrice()+"");
		ep_desc.setText(menu.getDescription());
		ep_remark.setText(menu.getRemark());
		if(menu.getStatus()==1) {
			cb_status.setSelected(true);
		}
		//显示菜品图片
		//创建一个icon图片
		ImageIcon icon=new ImageIcon(menu.getFoodIcon());
		icon.setImage(icon.getImage().getScaledInstance(250, 179, 1));
		//给lbl标签添加一个icon图标
		lbl_icon.setIcon(icon);
		lbl_icon.setText(menu.getFoodIcon());
	}
}
